package cn.lianyutiantang.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.*;

/**
 * Created by Linpeizhan on 7/16/15.
 */
public class JsonUtil {
    private static ObjectMapper mapper;

    /**
     * 获取ObjectMapper实例
     *
     * @param createNew 方式：true，新实例；false,存在的mapper实例
     * @return
     */
    public static synchronized ObjectMapper getMapperInstance(boolean createNew) {
        if (createNew) {
            return new ObjectMapper();
        } else if (mapper == null) {
            mapper = new ObjectMapper();
        }
        return mapper;
    }

    /**
     * map对象转成json字符串
     *
     * @param object map对象
     * @return map的json字符串
     */
    public static String mapToJson(Object object) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(object);
    }

    /**
     * list转成json字符串
     *
     * @param list list
     * @return list的json字符串
     */
    public static String listToJson(List list) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(list);
    }

    /**
     * 对象转成json字符串
     *
     * @param object 对象
     * @return 对象的json字符串
     */
    public static String objectToJson(Object object) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(object);
    }

    /**
     * 将json字符串转换成java对象
     *
     * @param json 准备转换的json字符串
     * @param cls  准备转换的类
     * @return
     * @throws Exception
     */
    public static Object jsonToBean(String json, Class<?> cls) throws Exception {
        try {
            ObjectMapper objectMapper = getMapperInstance(false);
            Object vo = objectMapper.readValue(json, cls);
            return vo;
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    /**
     * 将json字符串转换成java对象
     *
     * @param json      准备转换的json字符串
     * @param cls       准备转换的类
     * @param createNew ObjectMapper实例方式:true，新实例;false,存在的mapper实例
     * @return
     * @throws Exception
     */
    public static Object jsonToBean(String json, Class<?> cls, Boolean createNew) throws Exception {
        try {
            ObjectMapper objectMapper = getMapperInstance(createNew);
            Object vo = objectMapper.readValue(json, cls);
            return vo;
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    /**
     * 将Json对象转换成Map
     *
     * @param jsonString
     *            json对象
     * @return Map对象
     * @throws JSONException
     */
    public static Map toMap(String jsonString) throws JSONException {

        JSONObject jsonObject = new JSONObject(jsonString);

        Map result = new HashMap();
        Iterator iterator = jsonObject.keys();
        String key = null;
        String value = null;

        while (iterator.hasNext()) {

            key = (String) iterator.next();
            value = jsonObject.getString(key);
            result.put(key, value);

        }
        return result;

    }
    public static void ParseJson(String jsonString) throws JSONException,
            ParseException {

        JSONObject jo = new JSONObject(jsonString);
        JSONArray ja = jo.getJSONArray("map");

        System.out.println("\n将Json数据解析为Map：");
        System.out.println("phone: " + ja.getJSONObject(0).getString("phone")
                + " uname: " + ja.getJSONObject(0).getString("uname") + " msg: "
                + ja.getJSONObject(0).getInt("mag"));






    }

    public static void writeOutJsonData(HttpServletResponse response, Object data) throws IOException {
        try {
            response.setContentType("Content-Type=text/plain; charset=UTF-8");// CharacterEncoding
            PrintWriter out = response.getWriter();
            if (data instanceof ArrayList) {
                //JSONArray jsonArray = JSONArray.fromObject(data);

                out.write(JsonUtil.listToJson((List)data).toString());
            } else {
               /* JSONObject jsonObject = new JSONObject();
                jsonObject.put("result", data);
                String jsonStr = jsonObject.toString();*/
                out.write(JsonUtil.objectToJson(data));
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
